<?php

$server_name = $_SERVER['SERVER_NAME'];
$server_url = "http://" . $server_name;
//TODO: filter server_name


/**
 * Get request Cookie
*/
$cookie = "";
foreach ($_COOKIE as $key => $value) {
    $cookie = $cookie . $key . "=" . $value . ";";
}



$req_uri = $_SERVER['REQUEST_URI'];
$proxy_url = "http://zhangtielei.appspot.com";
$url = $proxy_url . $req_uri;
$method = $_SERVER['REQUEST_METHOD'];
$contentType = $_SERVER['CONTENT_TYPE'];

$ch = curl_init();

function writeCallback($ch,$string) {
    echo $string;
    return strlen($string);
}
function headerCallback($ch,$string) {
    global $proxy_url, $server_url;
    $hd = rtrim($string);
    if  (strlen($hd) > 0 && strpos($hd, "Encoding") === false && strpos($hd, "Length") === false) {
        if (strpos($hd, "Location") === 0) { //Redirect Location
            $hd = str_replace($proxy_url, $server_url, $hd);
        }
        header($hd);
    }
    return strlen($string);
}



$client_headers = array();
$client_headers['Cookie'] = $cookie;
//$client_headers['Cookie'] = $_COOKIE;

curl_setopt( $ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1" );
curl_setopt( $ch, CURLOPT_URL, $url );
if ($method === "POST") {
    curl_setopt( $ch, CURLOPT_POST, true );
    if ($contentType) {
        $postData = array();
        if (strpos($contentType, "multipart/form-data") === 0) {
            foreach($_POST as $key=>$value) {
            	  $value=str_replace("\\\"","\"",$value);
                $postData[$key] = $value;
            }
            foreach($_FILES as $key=>$value) {
                $postData[$key] = "@" . $value['tmp_name'];
            }
            curl_setopt( $ch, CURLOPT_POSTFIELDS, $postData );
        }
        else {
            foreach($_POST as $key=>$value) {
            	  $value=str_replace("\\\"","\"",$value);
                $postData[] = urlencode($key) . "=" . urlencode($value);
                curl_setopt($ch,CURLOPT_POSTFIELDS, implode('&',$postData));
            }
        }
        
    }

}
curl_setopt( $ch, CURLOPT_HTTPHEADER, $client_headers );
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, false );
curl_setopt( $ch, CURLOPT_ENCODING, "" );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_AUTOREFERER, true );
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );    # required for https urls
//curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, $timeout );
//curl_setopt( $ch, CURLOPT_TIMEOUT, $timeout );
curl_setopt( $ch, CURLOPT_MAXREDIRS, 10 );
curl_setopt( $ch, CURLOPT_WRITEFUNCTION, writeCallback );
curl_setopt( $ch, CURLOPT_HEADERFUNCTION, headerCallback );
curl_setopt( $ch, CURLOPT_COOKIE, $cookie); 


$content = curl_exec( $ch );
$response = curl_getinfo( $ch );
curl_close ( $ch );

?>